<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>onClickOutside</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: #2396ef;
            color: #fff;
        }
    </style>
</head>

<body>
    <div id="box" class="box">
        <p>点击我之外的区域试试看</p>
    </div>
    <script>
        const onClickOutside = (element, callback) => {
            document.addEventListener('click', e => {
                if (!element.contains(e.target)) {
                    callback();
                }
            })
        }
        onClickOutside(document.querySelector("#box"), () => {
            alert('You click outside!');
            console.log('hello');
        })
    </script>
</body>

</html>